﻿using System.Collections.Generic;
using MSP.Data.Domain;
using MSP.Data.NHibernate;
using MSP.Data.Repositories;
using MSP.Business.Logic;
using MSP.Data.Domain.Enums;

namespace MSP.Business.CustomerManagement
{
    public class CustomerManager
    {
        public int SaveCustomer(Customer customer)
        {
            int customerId = 0;

            if (customer != null)
            {
                using (var unitOfWork = new UnitOfWork(NHibernateSessionFactory.SessionFactory))
                {
                    var customerRepository = new CustomerRepository(unitOfWork.Session);
                    customerRepository.Save(customer);
                    unitOfWork.Commit();
                }

                customerId = customer.Id;
            }

            return customerId;
        }

        public int SaveOrUpdate(Customer customer)
        {
            int customerId = 0;

            if (customer != null)
            {
                using (var unitOfWork = new UnitOfWork(NHibernateSessionFactory.SessionFactory))
                {
                    var customerRepository = new CustomerRepository(unitOfWork.Session);
                    customerRepository.SaveOrUpdateCopy(customer);
                    unitOfWork.Commit();
                }

                customerId = customer.Id;
            }

            return customerId;
        }

        public bool UpdateCustomer(Customer customer)
        {
            bool result = false;

            using (var unitOfWork = new UnitOfWork(NHibernateSessionFactory.SessionFactory))
            {
                var customerRepository = new CustomerRepository(unitOfWork.Session);
                result = customerRepository.Update(customer);
                unitOfWork.Commit();
            }

            return result;
        }

        public bool DeleteCustomer(Customer customer)
        {
            bool result = false;
            using (var unitOfWork = new UnitOfWork(NHibernateSessionFactory.SessionFactory))
            {
                var customerRepository = new CustomerRepository(unitOfWork.Session);
                result = customerRepository.Delete(customer);
                unitOfWork.Commit();
            }

            return result;
        }

        public Customer GetCustomerById(int Id)
        {
            var customerRepository = new CustomerRepository(NHibernateSessionFactory.SessionFactory.OpenSession());
            Customer customer = customerRepository.GetCustomerById(Id);
            return customer;
        }

        public IList<Customer> GetAllCustomer()
        {
            var customerRepository = new CustomerRepository(NHibernateSessionFactory.SessionFactory.OpenSession());
            IList<Customer> customer = customerRepository.GetAllCustomer();

            return customer;
        }

    }
}
